const Koa = require('koa')
const koaBody = require('koa-body')
const koaStatic = require('koa-static')
const error = require('koa-json-error')
const parameter = require('koa-parameter')
const mongoose = require('mongoose')
const path = require('path')
const { DB_URL } = require('./config')
const app = new Koa()
const routing = require('./routes')
mongoose.connect(
  DB_URL,
  { useUnifiedTopology: true, useNewUrlParser: true },
  () => {
    console.log('MongoDB已经启动')
  }
)
mongoose.connection.on('error', console.error)
// 静态服务中间件写到最前面
app.use(koaStatic(path.join(__dirname, 'public')))
// 错误拦截中间件写到解析前面
app.use(
  error({
    postFormat: (e, { stack, ...rest }) =>
      process.env.NODE_ENV === 'production' ? rest : { stack, ...rest }
  })
)
// 请求体解析中间件
app.use(
  koaBody({
    multipart: true,
    formidable: {
      // 设置上传目录
      uploadDir: path.join(__dirname, 'public/uploads'),
      // 保留文件后缀
      keepExtensions: true
    }
  })
)
// 参数校验中间件
app.use(parameter(app))
// 注册路由
routing(app)
app.listen(3000, () => {
  console.log('服务已启动在3000端口')
})
